package cn.itcast.netty.practice;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

@Slf4j
public class EchoServer {

    public static void main(String[] args) {
        new ServerBootstrap()
            .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast("h1", new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            ByteBuf byteBuf = (ByteBuf) msg;
                            log.info("接收到消息：{}",byteBuf.toString(Charset.defaultCharset()));
                            // 建议使用这种方法创建ByteBuf
                            ByteBuf response = ctx.alloc().buffer();
                            response.writeBytes(byteBuf);
                            // 往channel里写(返回数据给客户端)
                            ctx.writeAndFlush(response);
                            // 释放ByteBuf，因为这里是最后一次使用
                            byteBuf.release();
                            response.release();
                        }
                    });
                }
            }).bind(8080);
    }
}
